package com.example.demomk.Fragment;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.demomk.Adapter.RuleAdapter;
import com.example.demomk.Interface.OnBottomBarListener;
import com.example.demomk.MainActivity;
import com.example.demomk.R;
import com.example.demomk.ViewModel.MeasurementViewModel;
import com.example.demomk.databinding.ActivityRuleBinding;
import com.example.demomk.databinding.FragmentRuleBinding;
import com.example.demomk.entity.AvgMeasurementWithMeasurements;

import java.util.concurrent.atomic.AtomicInteger;


public class RuleFragment extends Fragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private FragmentRuleBinding binding;
    private MeasurementViewModel viewModel;
    private RuleAdapter adapter;
    private RecyclerView recyclerView;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public RuleFragment() {
        // Required empty public constructor
    }


    public static RuleFragment newInstance(String param1, String param2) {
        RuleFragment fragment = new RuleFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        binding = FragmentRuleBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        FragmentActivity activity = requireActivity();

        viewModel = new ViewModelProvider(this).get(MeasurementViewModel.class);
        recyclerView = binding.ruleRecycler;
        adapter = new RuleAdapter();
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(requireActivity()));

        TextView dataText = binding.dataText;
        dataText.setSelected(true);


        recyclerView.addItemDecoration(new DividerItemDecoration(activity,DividerItemDecoration.VERTICAL));

        viewModel.getAvgDetails().observe(activity, avgList -> {
            if (avgList != null && !avgList.isEmpty()) {
                // 使用计数器确保所有详情加载完成
                AtomicInteger counter = new AtomicInteger(avgList.size());

                for (AvgMeasurementWithMeasurements item : avgList) {
                    viewModel.loadMeasurementDetails(item.avgMeasurement.getId());
                }

                // 观察measurementsMap的变化
                viewModel.getMeasurementsMap().observe(activity, map -> {
//                    if (map != null && map.size() == avgList.size()) {
////                        Log.d("measurementsMap", "All data loaded: " + map.get(1));
//                        //遍历出内容
//                        for (Map.Entry<Integer, List<Measurement>> entry : map.entrySet()) {
//                            int avgId = entry.getKey();
//                            List<Measurement> measurements = entry.getValue();
//                        }
//                    }
                    adapter.setData(avgList, map);
                });
            }
        });
        viewModel.getMeasurementCount().observe(activity, count -> {
            if (count != null) {
                binding.count.setText("样本数: "+String.valueOf(count));
            }
        });

        //复选框按钮
        onclick();

        //点击事件
        onclickListener();

        ruleoclick();

    }

    private void ruleoclick() {
        //点击事件
        if (requireActivity() instanceof OnBottomBarListener) {
            ((MainActivity) requireActivity()).setBottomBarprint(v -> {
                Toast.makeText(requireContext(), "常规视图按钮被点击", Toast.LENGTH_SHORT).show();
                // 执行刷新、跳转等操作
            });
        }
        //打印按钮
        if (requireActivity() instanceof OnBottomBarListener) {
            ((OnBottomBarListener) requireActivity()).setHomeButtonListener(v -> {
                Toast.makeText(requireContext(), "常规视图打印按钮被点击", Toast.LENGTH_SHORT).show();
            });
        }

    }

    private void onclick() {
        binding.checkAll.setOnClickListener(v -> {
            boolean isChecked = binding.checkAll.isChecked();
            adapter.selectAll(isChecked); // 调用适配器的全选方法
            binding.currentAll.setChecked(isChecked);
        });
        binding.currentAll.setOnClickListener(v -> {
            boolean isChecked = binding.currentAll.isChecked();
            adapter.selectAll(isChecked); // 调用适配器的全选方法
            binding.checkAll.setChecked(isChecked);
        });

        adapter.setOnItemSelectedListener((position, isChecked) -> {
            // 检查是否所有 item 都被选中
            boolean allHeadersSelected = adapter.areAllHeadersSelected(); // 只判断头部
            binding.checkAll.setChecked(allHeadersSelected);
            binding.currentAll.setChecked(allHeadersSelected);
        });
    }

    private void onclickListener() {
        binding.rule.setOnClickListener(v -> {
//            Fragment fragment = new HomeFragment();
//            loadFragment(fragment);
            requireActivity().getSupportFragmentManager().popBackStack();
        });
    }
    private void loadFragment(Fragment fragment) {
        requireActivity().getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fragment_container, fragment)
                .addToBackStack(null)
                .commit();
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}